<!--  -->
<template>
  <div>
    <c-title :hide="false" text="唇形匹配"></c-title>
      <van-pull-refresh v-model="pull_isLoading" @refresh="onRefresh">
      <div class="lip-box">
        <div class="lip-text">操作提示</div>
        <div class="choose-raido">
          <div class="choose-sp" :class="evOverlayIsShow() ? 'actvie-icon-cp' : ''">
            <i class="iconfont icon-wancheng2"></i>
            <span class="sp-name">勾选视频</span>
          </div>
          <div>
            <i class="iconfont icon-gengduo3" :class="evOverlayIsShow() ? 'actvie-icon-cp' : ''"></i>
          </div>
          <div class="choose-sp"  :class="showDialog ? 'actvie-icon-cp' : ''">
            <i class="iconfont icon-Icon_mouth"></i>
            <span class="sp-name">点击匹配</span>
          </div>
        </div>
      </div>
      <div style="padding: 0 0.8rem;">
        <d-list endText="" :loading="finished" :finished="finished" @load="onLoad">
          <div style="margin-top: 0.5rem; column-count: 2; gap: 0.6rem; padding: 0.1rem 0.25rem 0.25rem 0.25rem;">
            <div v-for="(item, index) in libList" :key="index" class="grid-child-custom bg-fff border-radius-10 flex-column relative" v-if="!item.hidden">
              <template v-if="!item.hidden">
                <div class="relative img-bg" style="min-height: 12rem;display: flex;align-items: center;">
                  <img v-if="item.cover_img" :src="item.cover_img" style="width: 100%;" />
                  <video
                    v-else
                    :src="item.url"
                    :style="{ width: '100%', height: item.url ? '100%' : '15rem' }"
                    class="w_h_100"
                  />
                  <div v-if="item.lip" class="flex-column flex-a-c flex-j-c block-center" :class="item.lip ? 'createStatusBlock' : ''">
                    <div v-if="item.lip.status == 0" style="display: flex;flex-direction: column;align-items: center;">
                      <img :src="`${imgPath}ai-create/ai-create-14.gif`" mode="widthFix" style="width: 1.5rem;" />
                      <div>唇形匹配中</div>
                    </div>
                    <div v-if="item.lip.status == 2">
                      <i class="iconfont icon-tishi2"></i>
                      <div>唇形匹配失败</div>
                    </div>
                    <div v-if="item.lip.status == 1">
                      <i @click="onPreviewVideo(item.url)"  class="iconfont icon-fabushipin f-40" style="text-shadow: #666666 0.025rem 0 0.25rem;"></i>
                    </div>
                  </div>
                  <span class="icon-sh"  v-if="item.is_lip_video"><i class="iconfont icon-yichunxingpipei" style="background: linear-gradient(330deg, #F98D20 0%, #FF112A 55%, #FF178B 100%); color: white"></i></span>
                </div>
                <div class="f-grow-1"></div>
                <div class="padding-10">
                  <div class="flex relative">
                    <div class="f-15 color-00001C f-grow-1 line-clamp-2 t-l">{{ item.name }}</div>
                    <i
                      v-if="item.has_operate && (!item.lip || (item.lip && item.lip.status != 0))"
                      @click="onClickLipDi(index, true)"
                      class="iconfont  icon-wancheng2 padding-left-6 color-AAAAB3"
                      :class="item.overlayIsShow ? 'actvie-icon-cp' : ''"
                    ></i>
                  </div>
                  <div class="flex-a-c margin-top-4" v-if="item.member">
                    <img :src="item.member ? item.member.avatar : ''" class="min-img" />
                    <div class="padding-left-6 f-12 ">{{ item.member ? item.member.nickname : "" }}</div>
                  </div>
                </div>
                <template v-if="item.overlayIsShow">
                  <div class="popover-group flex-column flex-a-c flex-j-c absolute t-l" @click="onClickLipDi(index, false)">
                    <van-cell class="popover-group-cell" title="唇形匹配" v-if="item.has_lip_match" @click.stop="onClickLip(item.duration,item.body,item.id)"  icon="iconfont icon-Icon_mouth" clickable>
                      <template #icon>
                        <i class="iconfont icon-Icon_mouth f-12 margin-right-4" style="margin-right: 0.2rem;"></i>
                      </template>
                    </van-cell>
                  </div>
                  <van-overlay class="absolute" :show="item.overlayIsShow" />
                </template>
              </template>
            </div>
          </div>
        </d-list>
        <van-empty image="search" v-if="libList.length == 0" description="暂无作品" />
      </div>
    </van-pull-refresh>

    <van-dialog use-slot title="提示" v-model="showDialog"  confirm-button-color='var(--themeBaseColor)'  show-cancel-button @confirm='onconfirmLip' confirm-button-text='确认匹配' >
      <div class="margin-12" style="text-align: left;">
        <div>本次生成将消耗{{lip_duration_unused_item}}秒唇形匹配创作权益，  剩余{{lip_duration_unused}}秒。
          <div class="themeColor">注：如需更改正脸参考图，请先在数字分身列表进行修改，再进行唇形匹配</div>
        </div>
      </div>
    </van-dialog>

    <van-popup v-model="showDigital"  class="pop-base-class" position="bottom" round style="background-color: #F5F5F5;" closeable @close="onClickVal('showDigital',false)" >
      <div class="pop-base-title">请编辑-正脸参考图</div>
      <div class="pop-base-content" style="padding: 0;text-align: left;">
        <van-cell-group inset>
          <van-cell title="分身名称" :value="lip_duration_unused_body ? lip_duration_unused_body.name : ''" />
          <van-cell title="数字分身" use-label-slot :border="false">
            <div slot="label">
              <div style="display: block;">
                <video :src="lip_duration_unused_body ? lip_duration_unused_body.url : ''" style="height: 2rem; width: 2rem;" />
              </div>
            </div>
          </van-cell>
          <van-cell title="正脸参考图" :border="false" use-label-slot>
            <div slot="label">
              <div style="display: block;">
                <van-uploader v-model="bodyReferImg" accept="image/jpeg, image/jpg, image/png, image/bmp, image/webp" use-before-read max-count="1"  :before-read="beforeReadReferImg" :after-read="uploadImageReferImg" :delete="onDelete"></van-uploader>
              </div>
              <div>
                图片要求：
              </div>
              <div>文件大小：小于等于10MB</div>
              <div>图像大小：长宽比小于等于 2，最大边长小于等 4096</div>
              <div>格式：jpeg、jpg、png、bmp、webp</div>
            </div>
          </van-cell>

        </van-cell-group>
      </div>
      <div class="pop-base-bottom">
        <van-button :disabled='!bodyReferImg || !bodyReferImg.length' @click="submitUploadReferImg" round color="var(--themeBaseColor)" type="danger" block >确认并提交</van-button>
      </div>
    </van-popup>

    <van-dialog use-slot title="提示" v-model="showDialogUnReferImg" confirm-button-text='去上传' cancel-button-text='不上传且匹配'   @cancel="submitLip"  @confirm='onClickVal("",true)' confirm-button-color='var(--themeBaseColor)'>
      <div class="margin-12" style="text-align: left;">
        <div><span class="themeColor">数字分身未上传正脸参考图！</span>若不上传人脸参考图，默认将选择视频中第一个有人脸的画面中，人脸占比最大的人物为目标，导致唇形匹配有误差，请确认是否去上传！。
          <div class="themeColor">本次生成将消耗{{lip_duration_unused_item}}秒唇形匹配创作权益，  剩余{{lip_duration_unused}}秒</div>
        </div>
      </div>
    </van-dialog>

    <van-popup v-model="previewMedia" position="center" round style="background-color: #000;width: 100%;" @close="oncloseMedia">
      <video :src="previewMediaUrl" controls style="width: 100%;"></video>
    </van-popup>
  </div>
</template>

<script>
import DList from "@/components/dlist";
export default {
  data() {
    return {
      active: 0,
      libList: [],
      page: 1,
      finished: false,
      business_id: 0,
      showDialog: false,
      pull_isLoading:false,
      showDigital: false,
      bodyReferImg: [],
      previewMediaUrl: "",
      previewMedia: false
    };
  },

  components: { DList },

  mounted() {
    this.business_id = this.$route.query.business_id || 0;
    this.fun.setWXTitle("唇形匹配");
    this.getData();
  },

  methods: {
    onClickLipDi(index, val) {

      for (let item of this.libList) {
        this.$set(item, "overlayIsShow", false);
      }
      if(index !== "") {
        this.$set(this.libList[index], "overlayIsShow", val);
      }
    },
    onClickVal(name, val) {
      this[name] = val;
    },
    onRefresh() {
      this.pull_isLoading = true;
      this.init();
    },
    onLoad() {
      this.getTabsList();
    },
    init() {
      this.page = 1;
      this.finished = false;
      this.libList = [];
      if( this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
      this.getTabsList();
    },
    async getData() {
      let { result, msg, data } = await $http.get(
        "plugin.ai-create.frontend.controllers.center.manage",
        {
          business_id: this.business_id || 0
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      this.imgPath = this.$store.state.imgPath;
      this.init();
      Object.assign(this, data);
    },
    async getTabsList() {
      if (this.finished) return; //没有更多
      let { result, msg, data } = await $http.get(
        "plugin.ai-create.frontend.controllers.video.lip-video",
        {
          business_id: this.business_id || 0,
          page: this.page
        },
        "."
      );
      if (result == 0) return this.$toast(msg);
      // 添加轮询请求数据
      if(!this.timer) {
        this.timer = setInterval(() => {
          let newArrStatus =  this.libList.filter(item => item.lip && item.lip.status == 0)
          this.getStatus(newArrStatus)
        }, 10000);
      }

      this.pull_isLoading = false;
      this.total = data.data.total;
      this.libList = this.libList.concat(data.data);
      if (data.current_page == data.last_page) {
        return (this.finished = true);
      }
      this.page += 1;
      console.log(this.page,'this.pagethis.page');
    },
    // 查询视频状态
    async getStatus(newArrStatus) {
      let { result, msg, data } = await $http.get(
        "plugin.ai-create.frontend.controllers.video.index.get-status",
        {
          ids : newArrStatus.map(item => item.id)
        },
      );
      if (result == 0) return this.$toast(msg);
      const newArrVideoList = this.replaceObjectsById(data,this.libList)
      this.$set(this, this.libList, newArrVideoList)
      this.$forceUpdate();
    },
    replaceObjectsById(sourceArray, targetArray) {
        // 遍历源数组中的每个对象
        sourceArray.forEach(sourceObj => {
            // 在目标数组中查找具有相同 id 的对象的索引
            const index = targetArray.findIndex(targetObj => targetObj.id === sourceObj.id);
            // 如果找到匹配的 id
            if (index!== -1) {
                // 用源数组中的对象替换目标数组中对应的对象
                targetArray[index] = sourceObj;
            }
        });
        return targetArray;
    },
    evOverlayIsShow() {
      let newArr = this.libList.some(item => item.overlayIsShow)
      return newArr || this.showDialog
    },
    onClickLip(duration, body, vid){
      for (let item of this.libList) {
        this.$set(item, "overlayIsShow", false);
      }
      if(!this.lip_duration_unused) {
        this.$dialog.confirm({
          title: '提示',
          message: '您的唇形匹配权益不足，无法进行匹配，请先进行充值！',
          confirmButtonText: '去充值'
        })
          .then(() => {
            this.$router.push(this.fun.getUrl("searchAll", "", {plugin_id: 198 }));
          })
          .catch(() => {
            // on cancel
          });
        return;
      }
      this.lip_duration_unused_item = duration;
      this.lip_duration_unused_body = body;
      this.lip_duration_unused_video_id = vid;
      this.showDialog = true;
    },
    // 嘴唇
    onconfirmLip() {
      if(!this.lip_duration_unused_body.refer_img) {
        // 分身的正脸参考图为空
        this.showDialogUnReferImg = true
        return;
      }
      this.submitLip();
    },
    async submitLip(){
      let _form = {
        video_id: this.lip_duration_unused_video_id
      }
      let  { result, msg, data }  = await $http.post(
        "plugin.ai-create.frontend.controllers.create.video.lip-match",
        {
          business_id: this.business_id || 0,
          form: _form
        },
        "."
      );
      this.$dialog.alert({
        title: '提示',
        message: '提交匹配' + msg,
      }).then(() => {
        // on close
      });
      this.init();
      this.lip_duration_unused_video_id = null;
      this.showDialogUnReferImg = false
    },
    // 前置校验方法
    async beforeReadReferImg (event) {
      return new Promise((resolve, reject) => {
        if (event.size > 10 * 1024 * 1024) {
          this.$toast('文件不能超过10MB');
          reject();
        } else {
          resolve();
        }
      });
    },
    // 上传文件
    uploadImageReferImg(file) {
      console.log(file,'filefile');
      const img = new Image();
      img.src = file.content;
      img.onload = () => {
        const ratio = Math.max(
          img.width / img.height,
          img.height / img.width
        )
        if (ratio > 2) {
          this.$toast('图片长宽比不能超过2:1')
          this.bodyReferImg = []
          return false
        }
        
        if (img.width > 4096 || img.height > 4096) {
          this.$toast('图片最大边长不能超过4096px')
          this.bodyReferImg = []
          return false
        }

        let uploadLoading = this.$toast.loading({
          message: "录音校验中",
          duration: 0
        });

        let fd = new FormData();
        fd.append("file", file.file);

        axios
          .post(this.fun.getRealUrl("upload.uploadPic"), fd, {
            headers: { "Content-Type": "multipart/form-data" }
          })
          .then(
            ({data}) => {
              console.log(data,'datadata',data.result);
              if (data.result == 1) {
                this.refer_img = data.data.img_url;
              } else {
                this.bodyReferImg = []
              }
              uploadLoading.clear();
            }
          )
          .catch(() => {
            this.$toast('上传失败')
            uploadLoading.clear();
          });

        console.log(ratio,'ratioratioratio');
      };
    },
    // 删除文件
    onDelete() {
      this.bodyReferImg = []
    },
    async submitUploadReferImg() {
      if (!this.bodyReferImg.length) {
        this.$toast('请先上传正脸参考图');
        return;
      }
      let  { result, msg, data }  = await $http.post(
        "plugin.ai-create.frontend.controllers.create.body-clone.upload-refer-img",
        {
          business_id: this.business_id || 0,
          refer_img: this.refer_img,
          id: this.lip_duration_unused_body.id
        },
        "."
      );
      this.$toast('编辑正脸参考图'+msg);
      if (!result) return;
      this['lip_duration_unused_body.refer_img'] = this.refer_img;
      this.showDigital = false;
      this.showDialog = this.lip_duration_unused_video_id?true: false
    },
    onPreviewVideo(url) {
      this.previewMediaUrl = url;
      this.previewMedia = true;
    },
    oncloseMedia(){
      this.previewMedia = false;
      this.previewMediaUrl = '';
    },
  },
  deactivated() {
    if( this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },

};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
.lip-box {
  background: white;
  margin: 0.8rem;
  padding: 0.8rem;
  text-align: left;
  border-radius: 0.5rem 0.5rem 0.5rem 0.5rem;
  .lip-text {
    font-weight: 800;
    font-size: 0.9rem;
  }
  .choose-raido {
    font-size: 0.8rem;
    display: flex;
    align-items: center;
    margin-top: 1rem;
    justify-content: space-around;
    .choose-sp {
      display: flex;
      align-items: center;
      justify-content: center;
      .icon-wancheng2 {
        font-size: 1.2rem;
      }
      .sp-name {
        margin-left: 0.4rem;
      }
    }
    .icon-gengduo3 {
      font-size: 0.7rem;
      color: #aaaab3;
    }
  }
}
.color-00001C {
  color: white;
}
.color-AAAAB3 {
  color: white;
  font-size: 1.4rem;
}

.bg-fff {
  background-color: #ffffff;
}
.border-radius-10 {
  border-radius: 0.625rem;
  overflow: hidden;
  margin-bottom: 0.6rem;
}

.padding-10 {
  padding: 0.625rem;
  background: rgba(0, 0, 0, 0.5);
  position: absolute;
  bottom: 0;
  width: 100%;
}

.padding-left-6 {
  padding-left: 0.375rem;
  color: white;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
}
.img-bg {
  background: #000;
}

.grid-child-custom {
  overflow: hidden;
}

.relative {
  position: relative;
}
.absolute {
  position: absolute !important;
}
.block-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 56px;
  color: #ffffff;
}
.createStatusBlock {
  background: rgba(0, 0, 0, 0.5);
  border-radius: 10px 10px 10px 10px;
}
img {
  display: block;
  margin: 0;
}

.min-img {
  width: 1.25rem;
  height: 1.25rem;
  border: 1px solid #d6d6dc;
  border-radius: 0.625rem;
}
.popover-group-cell {
  width: 7.5rem !important;
  padding: 4px 16px !important;
  border-radius: 16px !important;
  margin-bottom: 10px;
}
.popover-group {
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  flex-wrap: wrap;
}
.actvie-icon-cp {
  color: #3e66d6 !important;
}
.margin-12 {
  padding: 0.8rem;
  line-height: 2;
}
.icon-sh {
  position: absolute;
  right: 0;
  top: 0;
  width: 2rem;
  line-height: 1.5rem;
  height: 1.5rem;
  background: linear-gradient( 330deg, #F98D20 0%, #FF112A 55%, #FF178B 100%);
  border-radius: 0px 0.4rem 0px 0.4rem;
  color: #fff;
}
.line-clamp-2 {
  -webkit-line-clamp: 1;
}
</style>
